package com.atgm.mall.gmmailorder.listener;

import com.atgm.mall.gmmailorder.constant.OrderStatusEnum;
import com.atgm.mall.gmmailorder.dao.OrderDao;
import com.atgm.mall.gmmailorder.entity.OrderEntity;
import com.atgm.mall.gmmailorder.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 订单超时未支付，关闭
 */
@Slf4j
@Service
@RabbitListener(queues = "order.release.order.queue")
public class OrderCloseListener {

    @Autowired
    private OrderDao orderDao;

    @RabbitHandler
    public void closeOrder(String orderSn, Channel channel, Message message) {
        //开启ACK机制
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            //获取订单的状态
            QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id", "order_sn", "status");
            queryWrapper.eq("order_sn", orderSn);
            OrderEntity orderEntity = orderDao.selectOne(queryWrapper);
            if (null != orderEntity) {
                Integer status = orderEntity.getStatus();
                if (OrderStatusEnum.CREATE_NEW.getCode() == status) {
                    //关闭订单
                    OrderEntity updateOrder = new OrderEntity();
                    updateOrder.setId(orderEntity.getId());
                    updateOrder.setStatus(OrderStatusEnum.CLOSE.getCode());
                    orderDao.updateById(updateOrder);
                }
            }
        } catch (IOException e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException ex) {
                log.error("关闭订单失败");
            }
        }
    }

}
